package com.kingyun.gpsinspection.purificationservice.services.tdm.innerservice.impl;

import com.alibaba.fastjson.JSON;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.common.utils.FileTypeUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.ProblemAssignHistoryMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.TdmFileMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.TdmProblemMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.File;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.Employee;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EmployeeVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EntityVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.Organization;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.MessageImpartVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.Problem;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.ProblemAssignHistory;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.ProblemVo;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.OutEmployeeService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.OutEntityService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.OutOrganizationService;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.MessageImpartService;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.ProblemService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by sugongche on 2016/11/22.
 */
public class ProblemServiceImpl implements ProblemService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TdmProblemMapper tdmProblemMapper;
    @Autowired
    private TdmFileMapper tdmFileMapper;
    @Autowired
    private ProblemAssignHistoryMapper problemAssignHistoryMapper;
    @Autowired
    public MessageImpartService messageImpartService;
    @Autowired(required = false)
    public OutEmployeeService outEmployeeService;
    @Autowired(required = false)
    private OutEntityService outEntityService;
    @Autowired(required = false)
    public OutOrganizationService outOrganizationService;

    /**
     * 根据主键查询bean
     *
     * @param problemVo
     * @return
     */
    @Override
    public ProblemVo queryVoById(ProblemVo problemVo) throws Exception {
        if (null == problemVo) {
            return null;
        }
        ProblemVo reVo = tdmProblemMapper.selectByPrimaryKeyNew(problemVo);
        return reVo;
    }

    /**
     * 保存
     * 注意：解开启事务，不能抛异常
     *
     * @param employeeVo
     * @param problem
     * @param uploadFiles
     * @param deletedFiles
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int save(EmployeeVo employeeVo, Problem problem, String uploadFiles, String deletedFiles) {
        int a = 0;

        //设置问题所属组织
        setOrgIdByCondition(employeeVo, problem);
        problem.setProblemId(UniqueUtil.uuid());
        //设置创建时间
        problem.setCreateTime(new Date());
        //设置修改时间
        problem.setModifyTime(new Date());
        //更新问题状态
        problem.setStatus((short) 0);
        problem.setCreateUserId(employeeVo.getEmployeeId());
        problem.setModifyUserId(employeeVo.getEmployeeId());
        problem.setIsDelete((short) 0);
        //保存问题
        a += tdmProblemMapper.insert(problem);

        //插入指派历史表
        if (StringUtils.isNotBlank(problem.getAssignedPerson())) {
            ProblemAssignHistory history = new ProblemAssignHistory();
            history.setAssignHistoryId(UniqueUtil.uuid());
            history.setProblemId(problem.getProblemId());
            history.setAssignedPerson(problem.getAssignedPerson());
            a += problemAssignHistoryMapper.insertNew(history);

            //给处置人发送消息
            a += sendMessage(employeeVo, problem);
        }

        if (StringUtils.isNotBlank(uploadFiles)) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(uploadFiles, File.class);

            //重新设置附件属性
            for (int i = 0; i < listFiles.size(); i++) {
                File _file = listFiles.get(i);
                //设置主键
                _file.setFileId(UniqueUtil.uuid());
                //设置业务数据id
                _file.setBusinessId(problem.getProblemId());
                _file.setFileType((short) FileTypeUtil.getFileTypeByFileName(_file.getFileName()));
            }

            //必须判断非空
            if (listFiles != null && listFiles.size() > 0) {
                a += tdmFileMapper.insertByList(listFiles);
            }
        }

        //需要删除的附件信息
        if (StringUtils.isNotBlank(deletedFiles)) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(deletedFiles, File.class);
            if (listFiles != null && listFiles.size() > 0) {
                int len = listFiles.size();
                for (int i = 0; i < len; i++) {
                    File _file = listFiles.get(i);
                    a += tdmFileMapper.deleteByPrimaryKey(_file.getFileId());
                }
            }
        }

        return a;
    }

    /**
     * 更新
     *
     * @param employeeVo
     * @param problem
     * @param deletedFiles
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int update(EmployeeVo employeeVo, Problem problem, String uploadFiles, String deletedFiles) {
        if (problem == null) {
            return 0;
        }
        int a = 0;

        //修改时：数据库必须有记录，oldProblem!=null
        Problem oldProblem = tdmProblemMapper.selectByPrimaryKey(problem.getProblemId());

        //已经有处置人
        if (StringUtils.isNotBlank(oldProblem.getAssignedPerson())) {
            if (StringUtils.isNotBlank(problem.getAssignedPerson())) {
                //如果修改了处置人
                if (!oldProblem.getAssignedPerson().equals(problem.getAssignedPerson())) {
                    //给处置人发送消息
                    a += sendMessage(employeeVo, problem);

                    ProblemAssignHistory history = new ProblemAssignHistory();
                    history.setAssignHistoryId(UniqueUtil.uuid());
                    history.setProblemId(problem.getProblemId());
                    //新的处置人
                    history.setAssignedPerson(problem.getAssignedPerson());
                    a += problemAssignHistoryMapper.insertNew(history);
                }
            }
            //没有处置人：处置人开始是不必填的
        } else {
            //新添加处置人
            if (StringUtils.isNotBlank(problem.getAssignedPerson())) {
                //给处置人发送消息
                a += sendMessage(employeeVo, problem);

                ProblemAssignHistory history = new ProblemAssignHistory();
                history.setAssignHistoryId(UniqueUtil.uuid());
                history.setProblemId(problem.getProblemId());
                //新的处置人
                history.setAssignedPerson(problem.getAssignedPerson());
                a += problemAssignHistoryMapper.insertNew(history);
            }
        }

        //设置问题所属组织
        setOrgIdByCondition(employeeVo, problem);
        problem.setModifyUserId(employeeVo.getEmployeeId());
        a += tdmProblemMapper.updateByPrimaryKeyNew(problem);

        //更新附件信息
        if (StringUtils.isNotBlank(uploadFiles)) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(uploadFiles, File.class);
            if (listFiles != null && listFiles.size() > 0) {
                //重新设置附件属性
                String pId = problem.getProblemId();
                int len = listFiles.size();
                for (int i = 0; i < len; i++) {
                    File _file = listFiles.get(i);
                    //设置主键
                    _file.setFileId(UniqueUtil.uuid());
                    //设置业务数据id
                    _file.setBusinessId(pId);
                    _file.setFileType((short) FileTypeUtil.getFileTypeByFileName(_file.getFileName()));
                }
                a += tdmFileMapper.insertByList(listFiles);
            }
        }

        //需要删除的附件信息
        if (StringUtils.isNotBlank(deletedFiles)) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(deletedFiles, File.class);
            if (listFiles != null && listFiles.size() > 0) {
                int len = listFiles.size();
                for (int i = 0; i < len; i++) {
                    File _file = listFiles.get(i);
                    a += tdmFileMapper.deleteByPrimaryKey(_file.getFileId());
                }
            }
        }

        return a;
    }

    /**
     * 纳入隐患
     *
     * @return
     */
    @Override
    public int updateTrouble(Problem problem) {
        int a = 0;

        //更新问题状态
        problem.setStatus((short) 1);
        //更新是否纳入隐患和原因
        a += tdmProblemMapper.updateByPrimaryKeySelective(problem);

        return a;
    }

    /**
     * 设置问题对象组织
     *
     * @param employeeVo
     * @param problem
     */
    public void setOrgIdByCondition(EmployeeVo employeeVo, Problem problem) {
        //设置问题所属组织
        if (StringUtils.isNotBlank(problem.getProblemObject())) {
            try {
                EntityVo entityVo = outEntityService.getEntityByEntityId(problem.getProblemObject());
                //问题对象ID是生产实体
                if (entityVo != null) {
                    problem.setOrgId(entityVo.getParentOrgId());
                }
                //问题对象ID不是生产实体，而是组织ID
                Organization organization = outOrganizationService.queryOrganization(problem.getProblemObject());
                if (organization != null) {
                    problem.setOrgId(problem.getProblemObject());
                }
                if (entityVo == null && organization == null) {
                    problem.setOrgId(employeeVo.getOrgId());
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        } else {
            problem.setOrgId(employeeVo.getOrgId());
        }
    }

    /**
     * 指派工单处置人
     *
     * @param employeeVo
     * @param problem
     * @param problemAssignHistory
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int assign(EmployeeVo employeeVo, Problem problem, ProblemAssignHistory problemAssignHistory) {
        if (problem == null) {
            return 0;
        }

        int a = 0;

        Problem oldProblem = tdmProblemMapper.selectByPrimaryKey(problem.getProblemId());

        //指派处置人：必然已经有记录
        if (oldProblem != null) {
            //已经有处置人
            if (StringUtils.isNotBlank(oldProblem.getAssignedPerson())) {
                if (StringUtils.isNotBlank(problem.getAssignedPerson())) {
                    //如果修改了处置人
                    if (!oldProblem.getAssignedPerson().equals(problem.getAssignedPerson())) {
                        a += tdmProblemMapper.updateAssignedPersonById(problem);

                        //给处置人发送消息
                        a += sendMessage(employeeVo, problem);

                        //插入处置信息
                        problemAssignHistory.setAssignHistoryId(UniqueUtil.uuid());
                        a += problemAssignHistoryMapper.insertNew(problemAssignHistory);
                    }
                }
                //没有处置人：处置人开始是不必填的
            } else {
                //新添加处置人
                if (StringUtils.isNotBlank(problem.getAssignedPerson())) {
                    a += tdmProblemMapper.updateAssignedPersonById(problem);


                    //给处置人发送消息
                    a += sendMessage(employeeVo, problem);

                    //插入处置信息
                    problemAssignHistory.setAssignHistoryId(UniqueUtil.uuid());
                    a += problemAssignHistoryMapper.insertNew(problemAssignHistory);
                }
            }
        }

        return a;
    }

    /**
     * 给处置人发消息
     *
     * @param employeeVo
     * @param problem
     */
    public int sendMessage(EmployeeVo employeeVo, Problem problem) {
        int a = 0;

        //给处置人发送消息
        String content = "";
        String fmt = "yyyy-MM-dd HH:mm";
        SimpleDateFormat sdf = new SimpleDateFormat(fmt);
        String dateStr = sdf.format(new Date());
        Employee assginEmployee = outEmployeeService.findById(problem.getAssignedPerson());
        //审核人名称
        String auditor = assginEmployee == null ? "" : assginEmployee.getName();
        MessageImpartVo messageImpartVo = new MessageImpartVo();
        content = employeeVo.getName() + "于" + dateStr + "指派问题给" + auditor + "处置!";
        messageImpartVo.setMessageContent(content);
        //消息来源 0：任务，1：问题，2问题处置
        messageImpartVo.setMessageSource((short) 2);
        //消息推送目标人
        messageImpartVo.setUserId(problem.getAssignedPerson());
        a = messageImpartService.save(messageImpartVo);

        return a;
    }

    /**
     * 删除:软删除
     *
     * @param list
     * @return
     */
    @Override
    public int delByIds(List<String> list) throws Exception {
        if (list == null || (list != null && list.size() == 0)) {
            return 0;
        }

        int i = tdmProblemMapper.updateStateByIds(list);

        return i;
    }
}
